﻿using System;
using System.Collections.Generic;
using System.Text;


namespace Notepad_X.Classes {
    public class ICshartDocument : IDocument {

        private int _id;
        private Notepad_X.Components.TabPageX _tab_page;
        private string _path;
        private ICSharpCode.TextEditor.TextEditorControl _text_box;
        private bool _saved = false;
        private bool _available = false;

        private int _find_pos = 0;
        private int _find_index=0;
        private string _find_string = null;
        private bool _watcherChanged=false;
        private System.IO.FileSystemWatcher _watcher;


        public event DocumentXEventHandler DocumentChanged;

        public int id { get { return _id; } }
        public Notepad_X.Components.TabPageX tab_page { get { return _tab_page; } }
        public string path { get { return _path; } }

        public bool saved { get { return _saved; } }
        public bool available { get { return _available; } }

        public System.IO.FileSystemWatcher watcher { get { return _watcher; } set { _watcher = value; } }
        public bool watcherChanged { get{return _watcherChanged;} set{_watcherChanged=value;} }
        public System.Drawing.Printing.PrintDocument printDocument { get { return _text_box.PrintDocument; } }
        public object text_box { get { return _text_box; } }

        public System.Drawing.Font font { get { return _text_box.Font; } set { _text_box.Font = value; } }

        public void setColors(System.Drawing.Color Background, System.Drawing.Color Fore) {
            ICSharpCode.TextEditor.Document.HighlightingManager.Manager.DefaultHighlighting.SetColorFor("Default", new ICSharpCode.TextEditor.Document.HighlightColor(Fore, Background,  false, false));
        }

        public int find_pos { get { return _find_pos; } set { _find_pos = value; } }
        public int find_index { get { return _find_index; } set { _find_index = value; } }
        public string find_string { get { return _find_string; } set { _find_string = value; } }

        public string text { get { return _text_box.Document.TextContent; } set { _text_box.Document.TextContent = value; } }

        public ICshartDocument(int pId) {
            create(pId);
        }

        public void create(int pId){
            _id = pId;
            _tab_page = new Components.TabPageX(pId);
            _path = null;
            _text_box = new ICSharpCode.TextEditor.TextEditorControl();

            _tab_page.AllowDrop = true;
            _tab_page.Controls.Add(_text_box);
            _tab_page.id = _id;

            _text_box.Tag = _id;
            _text_box.Dock = System.Windows.Forms.DockStyle.Fill;
            //_text_box.Location = new System.Drawing.Point(0, 0);
            _text_box.ShowEOLMarkers = false;
            _text_box.ShowInvalidLines = false;
            _text_box.ShowSpaces = false;
            _text_box.ShowLineNumbers = false;
            _text_box.ShowHRuler = false;
            _text_box.ShowVRuler = false;
            _text_box.EnableFolding = false;
            _text_box.ActiveTextAreaControl.TextArea.AllowDrop = true;
            _text_box.AllowDrop = true;
            _text_box.ActiveTextAreaControl.Caret.PositionChanged += new EventHandler(Caret_PositionChanged);
            _saved = true;
            _available = false;
            _tab_page.ImageKey = "documentok";
            _watcher = null;
            _text_box.Document.DocumentChanged += new ICSharpCode.TextEditor.Document.DocumentEventHandler(Document_DocumentChanged);
        }

        void Caret_PositionChanged(object sender, EventArgs e) {
            try{
            Static.MainInstance.StatusBar_Line.Text = "Line : " + (_text_box.ActiveTextAreaControl.Caret.Line + 1) + " Col : " + (_text_box.ActiveTextAreaControl.Caret.Column + 1) + " Char : " + _text_box.ActiveTextAreaControl.Caret.Offset;
            }catch{}
        }

        void Document_DocumentChanged(object sender, ICSharpCode.TextEditor.Document.DocumentEventArgs e) {
            _saved = false;
            _tab_page.ImageKey = "documentchanged";
            _text_box.Document.DocumentChanged -= new ICSharpCode.TextEditor.Document.DocumentEventHandler(Document_DocumentChanged);
            if(DocumentChanged!=null) DocumentChanged.Invoke(this, new DocumentXEventArgs(_id));
        }

        //void ICshartDocument_DocumentChanged(object sender, DocumentXEventArgs e) {
        //    _saved = false;
        //    _tab_page.ImageKey = "documentchanged";
        //    DocumentChanged -= new DocumentXEventHandler(ICshartDocument_DocumentChanged); 
        //}

        public void clear(){
            _available = true;
            _text_box.Dispose();
            _text_box = null;
            _tab_page.Dispose();
            _tab_page = null;
            _path = null;
            _id = -1;
            _saved = false;
            DocumentChanged = null;
        }

        public void save(string pPath){
            _path = pPath;
            _text_box.SaveFile(pPath);
            _tab_page.ImageKey = "documentok";
            _saved = true;
            _text_box.Document.DocumentChanged += new ICSharpCode.TextEditor.Document.DocumentEventHandler(Document_DocumentChanged);
            //_text_box.Document.DocumentChanged += new ICSharpCode.TextEditor.Document.DocumentEventHandler(Document_DocumentChanged);
        }
        public void open(string pPath){
            _text_box.Document.DocumentChanged -= new ICSharpCode.TextEditor.Document.DocumentEventHandler(Document_DocumentChanged);
            _path = pPath;
            _text_box.LoadFile(_path, true, true);
           _tab_page.ImageKey = "documentok";
           _saved = true;
           _text_box.Document.DocumentChanged += new ICSharpCode.TextEditor.Document.DocumentEventHandler(Document_DocumentChanged);
          // _text_box.Document.HighlightingStrategy = ICSharpCode.TextEditor.Document.HighlightingManager.Manager.FindHighlighterForFile(_path);
        }

        public void cut(){
            _text_box.ActiveTextAreaControl.TextArea.ClipboardHandler.Cut(null, null);
        }
        public void copy(){
            _text_box.ActiveTextAreaControl.TextArea.ClipboardHandler.Copy(null, null);
        }
        public void paste(){
            _text_box.ActiveTextAreaControl.TextArea.ClipboardHandler.Paste(null, null);
        }
        public void selectAll(){
            _text_box.ActiveTextAreaControl.TextArea.ClipboardHandler.SelectAll(null, null);
        }

        public string selectedText() {
            if (_text_box.ActiveTextAreaControl.SelectionManager.HasSomethingSelected) {
                return _text_box.ActiveTextAreaControl.SelectionManager.SelectedText;
            }
            return null;
        }

        public void insert(int index, string text) {
            _text_box.Document.Insert(index, text); 
        }
        public int selectionIndex() {
           return _text_box.ActiveTextAreaControl.Caret.Offset; 
        }

        public void undo(){
            _text_box.Document.UndoStack.Undo();
        }
        public void redo(){
            _text_box.Document.UndoStack.Redo();        
        }

        public void print(){
            _text_box.PrintDocument.Print();
        }

        public void lineNumbers(bool value){
            _text_box.ShowLineNumbers = value;
        }

        public void goTo(int line){
          try {
                 _text_box.ActiveTextAreaControl.JumpTo(line - 1);
             }catch(Exception){}
        }

        public void find(string text){
            bool searchUp = true;

            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(text, System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            System.Text.RegularExpressions.Match match = null;
            System.Text.RegularExpressions.MatchCollection matchcollection = reg.Matches(_text_box.Document.TextContent.Substring(0, _text_box.ActiveTextAreaControl.Caret.Offset));
            if (text == _find_string) {
               _find_index++;
            } else {
               _find_index = 0;
               _find_string = text;
            }
            if (matchcollection.Count > 0 && _find_index < matchcollection.Count) {
                //match = matchcollection[matchcollection.Count - 1];
                if (_find_index == matchcollection.Count) {
                    _find_index = 0;
                }
                match = matchcollection[_find_index];
                system_find_highlight(match, searchUp);
            } else {
                matchcollection = reg.Matches(_text_box.Document.TextContent);
                if (matchcollection.Count > 0) {
                    if (_find_index >= matchcollection.Count) {
                        _find_index = 0;
                    }
                    match = matchcollection[_find_index];
                    system_find_highlight(match, searchUp);

                } else {
                    Notepad_X.Static.MainInstance.trace(Main.app_language[Strings.NotFound]);
                    _find_pos = 1;
                }
            }            
          
        }
        private void system_find_highlight(System.Text.RegularExpressions.Match match, bool searchUp)
	    {
            _text_box.ActiveTextAreaControl.SelectionManager.SetSelection(
            _text_box.Document.OffsetToPosition(match.Index), _text_box.Document.OffsetToPosition(match.Index + match.Length));
	        if (searchUp)
	        {
                _text_box.ActiveTextAreaControl.Caret.Position = _text_box.Document.OffsetToPosition(match.Index);
	        }
	        else
	        {
                _text_box.ActiveTextAreaControl.Caret.Position = _text_box.Document.OffsetToPosition(match.Index + match.Length);
	        }
            _find_pos = match.Index;
            _text_box.ActiveTextAreaControl.TextArea.Focus();
	    }
        public void replace(string text, string newText) {
    
            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(text, System.Text.RegularExpressions.RegexOptions.IgnoreCase);

            find(text);
            if (_find_pos != -1)
            {
                _text_box.ActiveTextAreaControl.Caret.Position =_text_box.Document.OffsetToPosition(_find_pos);
                string replaced = reg.Replace(_text_box.Document.TextContent, newText, 1, _find_pos);
                _text_box.Document.Replace(0, _text_box.Document.TextLength, replaced);
               
            }
            _text_box.ActiveTextAreaControl.TextArea.Focus();
  
        }
    }
}
